#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

#define NUM 128
#define SIZE 32
char command_line[NUM];
char* command_parse[SIZE];

int main()
{
	while(1)
	{
		memset(command_line,'\0',sizeof(command_line));
		printf("[lin@myhost 我的shell]$ ");
		fflush(stdout);

		if(fgets(command_line,NUM-1,stdin))
		{
			command_line[strlen(command_line)-1] = '\0';

			int index = 0;
			command_parse[index] = strtok(command_line," ");
			while(1)
			{
				command_parse[++index] = strtok(NULL," ");
				if(command_parse[index] == NULL)
					break;
			}

			if(strcmp(command_parse[0], "cd") == 0 && chdir(command_parse[1]) == 0)
				continue;
			if(fork() == 0)
			{
				//子进程
				execvp(command_parse[0],command_parse);
				exit(2);
			}
			int status = 0;
			pid_t ret = waitpid(-1,&status,0);
			if(ret > 0 && WIFEXITED(status))
			{
				printf("Exit Code: %d\n",WEXITSTATUS(status));
			}
		}
	}
	return 0;
}
